package org.platform.processor.diagnose.job;

import org.platform.constant.ExecutorStatus;
import org.platform.dao.mapper.FdTimingDiagnoseStrategyMapper;
import org.platform.mo.db.FdTimingDiagnoseStrategy;
import org.platform.processor.diagnose.DiagnoseTaskProcessor;
import org.platform.tool.helper.LogHelper;
import org.platform.tool.helper.ResourceHelper;
import org.quartz.InterruptableJob;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.MessageFormat;

/**
 * 创建诊断任务
 *
 * @author FengJie
 * @date 2018/8/18
 */
@Service
public class AddTestDiagnoseJob implements InterruptableJob {
    public static final String ID = "ID";

    @Autowired
    private DiagnoseTaskProcessor processor;
    @Autowired
    private FdTimingDiagnoseStrategyMapper strategyMapper;
    @Autowired
    private ResourceHelper resourceHelper;
    @Autowired
    private LogHelper logHelper;

    @Override
    public void interrupt() {

    }

    @Override
    public void execute(JobExecutionContext context) {
        String id = (String) context.getMergedJobDataMap().get(ID);
        FdTimingDiagnoseStrategy diagnoseStrategy = strategyMapper.selectByPrimaryKey(id);
        String diagnoseId = processor.addTestDiagnoseByKnowledgeID(diagnoseStrategy.getKnowledgeID(), diagnoseStrategy.getDeviceId(), resourceHelper.getStationName(), diagnoseStrategy.getType());

        Integer count = diagnoseStrategy.getCount();
        Integer exeCount = diagnoseStrategy.getExecutorStatus() + 1;
        if (count.equals(exeCount)) {
            diagnoseStrategy.setExecutorStatus(ExecutorStatus.completed.getValue());
        } else {
            diagnoseStrategy.setExecutorStatus(ExecutorStatus.executing.getValue());
        }
        diagnoseStrategy.setExecutorStatus(exeCount);
        DecimalFormat df = new DecimalFormat("0.000");
        diagnoseStrategy.setPassPercent(Double.valueOf(df.format((double) exeCount / (double) count)));
        strategyMapper.updateByPrimaryKeySelective(diagnoseStrategy);
        String content = MessageFormat.format("正在执行定时任务:{0},已执行第{1}次", diagnoseStrategy.getTestName(), exeCount);
        logHelper.normal(content, diagnoseId, diagnoseStrategy.getDeviceId());
    }


}
